package com.stone.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stone.bean.dto.RoleAddDTO;
import com.stone.bean.dto.RoleUpdateDTO;
import com.stone.config.SpringContextConfig;
import com.stone.config.exception.BusinessException;
import com.stone.entity.SysRole;
import com.stone.mapper.SysRoleMapper;
import com.stone.service.SysRoleService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author stone
 * @since 2022-04-02
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Override
    public void addRole(RoleAddDTO dto) {
        SysRole sysRole = JSON.parseObject(JSON.toJSONString(dto), SysRole.class);
        sysRole.setCreateBy(SpringContextConfig.loginUserId(dto.getToken()));
        sysRole.setCreateTime(LocalDateTime.now());
        if (sysRole.getOrderNum() < 0) {
            throw new BusinessException("排序不能为负数");
        }
        save(sysRole);
    }

    @Override
    public void updateRole(RoleUpdateDTO dto) {
        SysRole dbRole = getById(dto.getId());
        if (Objects.isNull(dbRole)) {
            throw new BusinessException("不存在的数据");
        }
        SysRole sysRole = JSON.parseObject(JSON.toJSONString(dto), SysRole.class);
        sysRole.setUpdateBy(SpringContextConfig.loginUserId(dto.getToken()));
        sysRole.setUpdateTime(LocalDateTime.now());
        if (sysRole.getOrderNum() < 0) {
            throw new BusinessException("排序不能为负数");
        }
        updateById(sysRole);
    }

    @Override
    public void delete(Long roleId) {
        removeById(roleId);
    }
}
